package antani.client;

import antani.client.pages.AlbumsPage;
import antani.client.pages.ArtistsPage;
import antani.client.pages.Page;
import antani.client.pages.PlayOpenPopup;
import antani.client.pages.PlayerPage;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootPanel;

@SuppressWarnings("unchecked")
public class GWTClient implements EntryPoint, ValueChangeHandler {

	RootPanel listPanel = RootPanel.get("albumTable");
	RootPanel mainPanel = RootPanel.get("mainTable");

	RootPanel currentPanel = null;

	Page currentPage = null;

	public static PlayerPage playerPage;
	public static AlbumsPage albumsPage;
	public static ArtistsPage artistsPage;

	static GWTClient instance;
	static HandlerRegistration registration;

	public static PlayOpenPopup playOpenPopup;

	public void onModuleLoad() {
		instance = this;

		playerPage = new PlayerPage(mainPanel);
		albumsPage = new AlbumsPage(listPanel);
		artistsPage = new ArtistsPage(listPanel);
		playOpenPopup = new PlayOpenPopup();

		String initToken = History.getToken();
		if (initToken.length() == 0) {
			History.newItem("player");
		}

		currentPage = playerPage;

		// Add history listener
		registration = History.addValueChangeHandler(this);

		// Now that we've setup our listener, fire the initial history state.
		History.fireCurrentHistoryState();
	}

	// private static int stackCounter = 0;

	@Override
	public void onValueChange(ValueChangeEvent event) {
		String pan = (String) event.getValue();
		System.out.println(pan);

		if (currentPage != null)
			currentPage.deactivate();

		if ("player".equals(pan)) {
			currentPage = playerPage;
		} else if ("albums".equals(pan)) {
			albumsPage.mode = AlbumsPage.MODE_ALL;
			currentPage = albumsPage;
		} else if ("random".equals(pan)) {
			albumsPage.mode = AlbumsPage.MODE_RANDOM;
			currentPage = albumsPage;
		} else if ("timeline".equals(pan)) {
			albumsPage.mode = AlbumsPage.MODE_TIMELINE;
			currentPage = albumsPage;
		} else if ("artists".equals(pan)) {
			currentPage = artistsPage;
		} else if (pan.startsWith("artist=")) {
			albumsPage.mode = AlbumsPage.MODE_ARTIST;
			albumsPage.filter = pan;
			currentPage = albumsPage;
		}
		currentPage.activate();

		// if (!"player".equals(pan))
		// stackCounter++;
	}

	public static void goToPlayer() {
		History.newItem("player");
		// registration.removeHandler();
		// for (int i = 0; i < stackCounter; i++) {
		// History.back();
		// }
		// stackCounter = 0;
		//
		// registration = History.addValueChangeHandler(instance);
	}
}
